-- 引入 socket 库
local os = require("os")
local inifile = require("inifile")
local socket = require("socket")  --调用socket包

local config_file = arg[1]
local init_config = inifile.parse(config_file)

local ip = init_config["RSYNC_SERVER"]["RSYNC_SERVER_IP"]    --程序设置要了解的server端的ip地址
local port = init_config["RSYNC_SERVER"]["RSYNC_SERVER_PORT"] --设置端口
-- 创建 TCP 服务器
local server = assert(socket.bind(ip, port))

local recv_count_limits = 10

local recv_events = { [1] = server }

local function find_avaliable_events_index()
    for i = 1, recv_count_limits, 1 do
        if recv_events[i] == nil then
            return i
        end
    end
    return -1
end

local function find_param_index(client)
    for i = 1, recv_count_limits, 1 do
        if recv_events[i] == client then
            return i
        end
    end
    return -1
end



print("wait client connect")
-- 启动服务器
while true do
    local recvs, _, status = socket.select(recv_events, nil, -1)
    for _, event_fd in ipairs(recvs) do
        -- 如果是服务器标识符
        local recv_event_id = find_param_index(event_fd)
        if recv_event_id == 1 then
            local client = server:accept()
            local now_index = find_avaliable_events_index()
            if now_index < 0 then
                client:close()
                goto end_loop_nested
            end
            recv_events[now_index] = client
        else
            local run_cmd, err = event_fd:receive()
            if not err then
                print(string.format("get command:[%s]", run_cmd))
                -- 发送给所有的客户端
                for i = 2, recv_count_limits, 1 do
                    if recv_events[i] ~= nil then
                        recv_events[i]:send(run_cmd .. "\n")
                    end
                end
                goto end_loop_nested
            end
            if err == "closed" then
                event_fd:close()
                if recv_event_id > 1 then
                    recv_events[recv_event_id] = nil
                end
                print("disconnect:" .. err)
                break
            else
                print("receive error:" .. err)
            end
        end
        ::end_loop_nested::
    end
    print("now recv_events size:" .. #recv_events)
end